<template>
  <div class="salary-discussion">
    <!-- <h1 class="section-title" v-if="!companyId">薪酬讨论</h1> -->
    <ZuiXinChou />
    <!-- 使用Element Grid实现双列布局 -->
    <el-row :gutter="20" class="salary-grid">
      <!-- 左侧列 -->
      <el-col :span="12" class="left-column">
        <salary-card 
          v-for="(item, index) in leftColumnItems" 
          :key="index"
          :data="item"
        />
      </el-col>
      
      <!-- 右侧列 -->
      <el-col :span="12" class="right-column">
        <salary-card 
          v-for="(item, index) in rightColumnItems" 
          :key="index"
          :data="item"
        />
      </el-col>
    </el-row>
    
    <!-- 加载指示器 -->
    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error">
      <el-alert
        :title="error"
        type="error"
        show-icon
        :closable="false"
      />
    </div>
    
    <div class="pagination" v-if="totalPages > 1">
      <button 
        :disabled="currentPage === 1" 
        @click="changePage(currentPage - 1)"
        class="page-btn"
      >
        上一页
      </button>
      
      <span class="page-info">
        第 {{ currentPage }} 页，共 {{ totalPages }} 页
      </span>
      
      <button 
        :disabled="currentPage === totalPages" 
        @click="changePage(currentPage + 1)"
        class="page-btn"
      >
        下一页
      </button>
    </div>

  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue';
import SalaryCard from '../components/SalaryCard.vue';
import { SalariesdataApi } from '../utils/api';
import ZuiXinChou from '@/components/ZuiXinChou.vue'

export default {
  name: 'SalaryDiscussion',
  components: {
    SalaryCard,
    ZuiXinChou
  },
  props: {
    companyId: {
      type: String,
      default: null
    }
  },
  setup(props) {
    const salaryData = ref([]);
    const loading = ref(false);
    const error = ref(null);
    const total = ref(0);
    const currentPage = ref(1);
    const pageSize = ref(10);
    
    // 获取薪酬数据
    const fetchSalaryData = async (page = 1) => {
      try {
        loading.value = true;
        error.value = null;
        
        const params = {
          skip: (page - 1) * pageSize.value,
          limit: pageSize.value
        };
        
        let response;
        if (props.companyId) {
          // 如果提供了公司ID，则获取该公司的薪酬数据
          response = await SalariesdataApi.getSalaryByCompanyId(props.companyId, params);
        } else {
          // 否则获取所有薪酬数据
          response = await SalariesdataApi.getDataList(params);
        }
        
        // 根据实际返回结构调整
        if (response.data) {
          salaryData.value = response.data;
          total.value = response.count || response.data.length;
        } else {
          salaryData.value = response.items || response;
          total.value = response.total || salaryData.value.length;
        }
        
        // 将API返回的数据映射到组件需要的格式
        salaryData.value = salaryData.value.map(item => ({
          id: item.id, // 添加ID字段
          title: item.title,
          company: item.company?.name || '',
          logo: item.company?.logo_url || '',
          position: item.level?.typical_title || item.department || '',
          level: item.level?.level_code || '',
          city: item.location || '',
          country: item.country || '',
          total: item.total_comp > 0 ? `￥${(item.total_comp / 10000).toFixed(1)}万${item.currency_code === 'CNY' ? '人民币' : item.currency_code}/年` : '面议',
          monthly: item.base_monthly_comp > 0 ? `￥${(item.base_monthly_comp / 10000).toFixed(1)}万x${item.base_monthly_comp_multiplier}薪` : '面议',
          stock: item.stock_comp > 0 ? `￥${(item.stock_comp / 10000).toFixed(1)}万/年` : '￥0万/年',
          likes: item.accuracy_upvote || 0,
          comments: item.comments || 0, // API提供评论数
          timeAgo: getTimeAgo(item.created_at),
          workHours: item.hour_per_week > 0 ? `${item.hour_per_week}` : null
        }));
      } catch (err) {
        console.error('获取薪酬数据失败:', err);
        error.value = '获取薪酬数据失败，请稍后重试';
      } finally {
        loading.value = false;
      }
    };
    
    // 计算时间差
    const getTimeAgo = (dateString) => {
      if (!dateString) return '未知时间';
      
      const date = new Date(dateString);
      const now = new Date();
      const diffInHours = Math.floor((now - date) / (1000 * 60 * 60));
      
      if (diffInHours < 1) {
        return '刚刚';
      } else if (diffInHours < 24) {
        return `${diffInHours}小时前`;
      } else {
        const diffInDays = Math.floor(diffInHours / 24);
        return `${diffInDays}天前`;
      }
    };
    
    // 将数据分为左右两列
    const leftColumnItems = computed(() => 
      salaryData.value.filter((_, index) => index % 2 === 0)
    );
    
    const rightColumnItems = computed(() => 
      salaryData.value.filter((_, index) => index % 2 !== 0)
    );
    
    // 总页数
    const totalPages = computed(() => {
      return Math.ceil(total.value / pageSize.value);
    });
    
    // 处理分页变化
    const changePage = (page) => {
      if (page >= 1 && page !== currentPage.value) {
        currentPage.value = page;
        fetchSalaryData(page);
      }
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchSalaryData(currentPage.value);
    });
    
    // 监听companyId变化
    watch(() => props.companyId, (newVal, oldVal) => {
      if (newVal !== oldVal) {
        currentPage.value = 1;
        fetchSalaryData(currentPage.value);
      }
    });

    return {
      leftColumnItems,
      rightColumnItems,
      loading,
      error,
      total,
      currentPage,
      pageSize,
      totalPages,
      changePage
    };
  }
};
</script>

<style scoped>
.salary-discussion {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.section-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 24px;
  color: #333;
}

.salary-grid {
  margin-bottom: 30px;
}

.left-column, .right-column {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.loading {
  text-align: center;
  padding: 20px;
}

.error {
  padding: 20px 0;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
  margin: 30px 0;
}

.page-btn {
  padding: 8px 16px;
  background-color: #f0f0f0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.page-btn:hover:not(:disabled) {
  background-color: #e0e0e0;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-info {
  font-size: 14px;
  color: #666;
}
</style>